@echo off
chcp 65001 >nul
echo ========================================
echo    Cloudflare Tunnel Setup Script
echo ========================================
echo.

REM 检查当前目录是否有 cloudflared.exe
if not exist "cloudflared.exe" (
    echo [ERROR] cloudflared.exe not found in current directory
    echo Please download from: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/
    pause
    exit /b 1
)

echo [INFO] cloudflared.exe found in current directory
echo.

REM 提示用户输入域名
set /p DOMAIN="Please enter your domain (e.g., api.yourdomain.com): "
if "%DOMAIN%"=="" (
    echo [ERROR] Domain cannot be empty
    pause
    exit /b 1
)

echo.
echo [Step 1/5] Login to Cloudflare...
.\cloudflared.exe tunnel login
if %errorlevel% neq 0 (
    echo [ERROR] Cloudflare login failed
    pause
    exit /b 1
)

echo.
echo [Step 2/5] Creating tunnel...
set TUNNEL_NAME=dify-kb-api-%RANDOM%
.\cloudflared.exe tunnel create %TUNNEL_NAME%
if %errorlevel% neq 0 (
    echo [ERROR] Tunnel creation failed
    pause
    exit /b 1
)

echo.
echo [Step 3/5] Getting tunnel information...
for /f "tokens=1" %%i in ('.\cloudflared.exe tunnel list ^| findstr %TUNNEL_NAME%') do set TUNNEL_ID=%%i

if "%TUNNEL_ID%"=="" (
    echo [ERROR] Cannot get tunnel ID
    pause
    exit /b 1
)

echo [INFO] Tunnel ID: %TUNNEL_ID%

echo.
echo [Step 4/5] Configuring DNS record...
.\cloudflared.exe tunnel route dns %TUNNEL_ID% %DOMAIN%
if %errorlevel% neq 0 (
    echo [ERROR] DNS configuration failed
    pause
    exit /b 1
)

echo.
echo [Step 5/5] Generating configuration file...

REM 创建配置文件
(
echo # Cloudflare Tunnel Configuration - Auto Generated
echo tunnel: %TUNNEL_ID%
echo credentials-file: %USERPROFILE%\.cloudflared\%TUNNEL_ID%.json
echo.
echo ingress:
echo   - hostname: %DOMAIN%
echo     service: http://127.0.0.1:5000
echo     originRequest:
echo       httpHostHeader: %DOMAIN%
echo       connectTimeout: 30s
echo       noTLSVerify: false
echo.
echo   - service: http_status:404
echo.
echo loglevel: info
echo protocol: quic
echo retries: 3
) > cloudflare-tunnel-generated.yml

echo.
echo ========================================
echo           Setup Complete!
echo ========================================
echo Tunnel Name: %TUNNEL_NAME%
echo Tunnel ID: %TUNNEL_ID%
echo Domain: %DOMAIN%
echo Config File: cloudflare-tunnel-generated.yml
echo.
echo Start Commands:
echo .\cloudflared.exe tunnel --config cloudflare-tunnel-generated.yml run
echo.
echo Or run in background:
echo .\cloudflared.exe service install
echo .\cloudflared.exe --config cloudflare-tunnel-generated.yml service install
echo.
pause